package com.stefan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ShortListServiceImpl {
    private static final String SHORTLIST_KEY_PREFIX = "shortlist:";
    private static final int LIMIT = 10; // 假设每个用户最多收藏100个商品
    @Autowired
    private RedisTemplate redisTemplate;
    public void addProduct(String customerId,String productId) {
        // 将商品添加到用户的收藏列表中
        if (redisTemplate.opsForList().size(SHORTLIST_KEY_PREFIX + customerId) == LIMIT) {
            // 如果用户的收藏列表已满，移除最旧的商品
            redisTemplate.opsForList().rightPop(SHORTLIST_KEY_PREFIX + customerId);
        }
        redisTemplate.opsForList().leftPush(SHORTLIST_KEY_PREFIX + customerId, productId);
    }
    public long removeProduct(String customerId, String productId) {
        // 从收藏夹里面删除某个商品
        return redisTemplate.opsForList().remove(SHORTLIST_KEY_PREFIX + customerId, 1, productId);
    }
    public List<String> getAllProducts(String customerId) {
        // 获取用户收藏列表中的所有商品
        return (List<String>) redisTemplate.opsForList().range(SHORTLIST_KEY_PREFIX + customerId, 0, -1);
    }
}
